package linc.cool.lock;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * @author yqlin
 * @date 2021/12/27 11:35 PM
 * @description 自定义独占锁
 */
public class MyLock extends AbstractQueuedSynchronizer {

    @Override
    protected boolean tryAcquire(int arg) {
        // CAS 加锁 state = 0
        if (this.compareAndSetState(0, 1)) {
            // 设置独占线程
            this.setExclusiveOwnerThread(Thread.currentThread());
            return true;
        }
        return false;
    }

    @Override
    protected boolean tryRelease(int arg) {
        // 释放锁
        // 释放锁为什么不用CAS? 因为加锁和解锁是成对出现的,不可能没加锁的也可以去解锁
        this.setExclusiveOwnerThread(null);
        this.setState(0);
        return true;
    }

    public void lock() {
        this.acquire(1);
    }

    public boolean tryLock() {
        return tryAcquire(1);
    }

    public void unlock() {
        release(1);
    }

    public boolean isLocked() {
        return isHeldExclusively();
    }

}

